<template>
  <view class="container">
    <uni-segmented-control
      :current="currentIndex"
      :values="items"
      style-type="text"
      active-color="#007aff"
      @clickItem="onClickItem"
    />
    <view v-if="currentIndex === 0">
      <view style="padding-top: 10px;"></view>
      <uni-forms
        ref="baseForm"
        :modelValue="liuzhuanForm"
        labelPosition="left"
        border
        labelWidth="100px"
      >
        <view style="padding-top: 10px;"></view>

        <uni-forms-item label="申请部门" required>
          <uni-easyinput type="text" v-model="liuzhuanForm.departmentName" disabled />
        </uni-forms-item>
        <uni-forms-item label="申请人">
          <uni-easyinput type="text" v-model="liuzhuanForm.name" disabled />
        </uni-forms-item>

        <uni-forms-item label="申请主题" required>
          <uni-easyinput @change="chuanci2" @input="chuanci2" v-model="liuzhuanForm.title" />
        </uni-forms-item>
        <!-- 上传照片 -->
        <!-- 图片上传模块 -->
        <uni-forms-item label="上传图片"></uni-forms-item>
        <uni-row>
          <uni-col :span="8" v-for="(item, idx) in liuzhuanForm.imgAccessoryBeans">
            <view class="img-res" @click="showBigImg(liuzhuanForm.imgAccessoryBeans,idx)">
              <image :src="liuzhuanForm.imgAccessoryBeans[idx].url" :key="idx" />
            </view>
          </uni-col>
        </uni-row>
        <button @click="clickSelectPic" style="margin-top:20rpx" class="btn-add">添加图片</button>
        <!-- 附件模块 -->
        <uni-forms-item label="上传附件"></uni-forms-item>
        <uni-row>
          <lsj-upload
            v-show="liuzhuanForm.accessoryBeans.length == 0"
            style="position:absolute !important;  z-index: 10; !important"
            ref="lsjUpload"
            childId="upload1"
            :size="uploadconfig3.size"
            :instantly="uploadconfig3.instantly"
            :formats="uploadconfig3.formats"
            :option="option"
            @change="onChange"
            @uploadEnd="onuploadEnd"
            @fail="failFile"
          >
            <button class="btn-fujian" @click="fuckyou">添加附件</button>
          </lsj-upload>
        </uni-row>

        <view v-if="liuzhuanForm.accessoryBeans.length">
          <view class="file_list" v-for="(item, index) in liuzhuanForm.accessoryBeans" :key="index">
            <!--  @click="prevFileClick(item.url, item.name)" -->

            <view style="display: flex; align-items: center; color: #0b847b">
              <view @click="prevFileClick(item)" class="file_list_item">
                <view>
                  <i class="iconfont icon-24gf-folderOpen" style="color: #0b847b"></i>
                  {{ item.name }}
                </view>
              </view>
              <view
                class="iconfont icon-close"
                style="color: #e86565;margin-left:5px"
                @click="delFile(index)"
              ></view>
            </view>
          </view>
        </view>

        <!-- 选人模块 -->
        <uni-forms-item label="审核人" required style="margin-top:60rpx"></uni-forms-item>
        <view v-for="(item, idx) in liuzhuanForm.auditors" :key="idx">
          <uni-row>
            <uni-col :span="10">
              <view v-if="idx>0" class="step-arrow">
                <uni-icons type="bottom" size="mini" color="#a5eaff"></uni-icons>
              </view>
            </uni-col>
          </uni-row>
          <view class="step">
            <uni-row>
              <uni-col :span="10">
                <view class="step-info-left">{{item.stepName}}</view>
              </uni-col>
              <uni-col :span="14">
                <view class="step-info-right">{{item.name}}</view>
              </uni-col>
            </uni-row>
          </view>
        </view>
        <!-- 承办选人模块 -->
        <!-- <uni-forms-item label="承办人" required style="margin-top:30rpx"></uni-forms-item>
        <view v-for="(item, idx) in liuzhuanForm.auditors" :key="idx">
          <uni-row>
            <uni-col :span="10">
              <view v-if="idx>0" class="step-arrow">
                <uni-icons type="bottom" size="mini" color="#a5eaff"></uni-icons>
              </view>
            </uni-col>
          </uni-row>
          <view class="step">
            <uni-row>
              <uni-col :span="10">
                <view class="step-info-left">{{item.stepName}}</view>
              </uni-col>
              <uni-col :span="14">
                <view class="step-info-right">{{item.name}}</view>
              </uni-col>
            </uni-row>
          </view>
        </view>-->
        <view style="padding-top: 30px;"></view>
        <button type="primary" @click="clickApply">提交</button>
      </uni-forms>
    </view>
    <view v-if="currentIndex === 1">
      <view>
        <uni-search-bar
          v-model="keyword"
          radius="100"
          placeholder="输入文件关键字"
          cancelButton="none"
          @confirm="search"
        />
      </view>
      <view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
        <!-- {{item}} -->
        <view class="card" @click="seeDetail(idx,item)">
          <view class="card-title">
            <uni-row>
              <uni-col :span="20">
                <view class="card-title-left">&nbsp;{{item.title}}</view>
              </uni-col>
              <uni-col :span="4">
                <view class="card-title-right">
                  <uni-tag text="审核" size="mini" type="warning" v-if="item.approvalState===0"></uni-tag>
                  <uni-tag text="通过" size="mini" type="primary" v-if="item.approvalState===1"></uni-tag>
                  <uni-tag text="拒绝" size="mini" type="error" v-if="item.approvalState===2"></uni-tag>
                  <uni-tag text="撤销" size="default" type="default" v-if="item.approvalState===3"></uni-tag>
                </view>
              </uni-col>
            </uni-row>
          </view>
          <view class="card-body">
            <view>主题：{{item.title}}</view>
          </view>
          <view class="card-footer">
            <uni-row>
              <uni-col :span="12">
                <view class="card-footer-left">{{item.createBy}}</view>
              </uni-col>
              <uni-col :span="12">
                <view
                  class="card-footer-right"
                >{{getFormatedTimeStr(item.createTime,"YYYY-MM-DD hh:mm:ss")}}</view>
              </uni-col>
            </uni-row>
          </view>
        </view>
      </view>
      <uni-load-more :status="moreStatus"></uni-load-more>
    </view>
  </view>
</template>
  
  <script>
import moment from "moment";
import { websock } from "../../net/websock";
import {
  prevFile // 预览文件
} from "../../utils/preview.js";
import { addxuanchuan, getxuanchuanList } from "../../net/xuanchuanbaodao.js";
import { serverUrl2, uploadconfig3, uploadconfig4 } from "../../const";
import { quchongAuditors } from "../../utils/util";

export default {
  data() {
    return {
      // 上传参数部分没有事情不要乱动
      uploadconfig3,
      uploadconfig4,
      option: {
        url: uploadconfig3.url,
        name: "file",
        header: { Authorization: uni.getStorageSync("token"), platform: 'APP' },
        formData: {}
      },
      userInfo: {},
      taskInfo: {},
      total: 1, //当前页
      pageSize: 10,
      pageNum: 1,
      formats: uploadconfig3.formats,
      instantly: uploadconfig3.instantly,
      size: uploadconfig3.size,
      // files: new Map(),
      // 上传参数部分没有事情不要乱动
      items: ["发起提交", "查看数据"],
      currentIndex: 0,
      moreStatus: "more",
      applyRecord: [],
      keyword: "",
      suffix: "",
      files: new Map(),
      liuzhuanForm: {
        uid: "",
        departmentId: "",
        departmentName: "",
        name: "",
        title: "",
        accessoryBeans: [],
        imgAccessoryBeans: [],
        auditors: []
      }
    };
  },
  async onLoad() {
    try {
      this.userInfo = await websock.getUserInfo();
      // this.taskInfo = await websock.getTaskDetail({ id: "25" });
      // console.log(this.taskInfo);
      this.liuzhuanForm.departmentName = this.userInfo.departmentName;
      this.liuzhuanForm.departmentId = this.userInfo.department;
      this.liuzhuanForm.name = this.userInfo.name;
      this.liuzhuanForm.uid = this.userInfo.uid;
      console.log("user info", this.userInfo);
    } catch (err) {
      console.error(err);
    }
  },
  async onReady() {
    // this.getNewestRecord();
    let auditors = await websock.getAuditors({ typ: 25 });
    console.log(auditors);
    quchongAuditors(auditors);
    this.liuzhuanForm.auditors = auditors;
    console.log(this.liuzhuanForm.auditors);
    this.getNewestRecord();
  },
  // 下拉刷新，获取最新的数据
  onPullDownRefresh() {
    if (this.currentIndex == 0) {
      uni.stopPullDownRefresh();
    } else {
      this.pageNum = 1;
      this.getNewestRecord();
    }
  },
  // 上拉刷新，获取历史数据
  onReachBottom() {
    if (this.currentIndex == 1) {
      if (this.moreStatus == "more") {
        uni.showLoading({
          title: "加载中"
        });
        this.pageNum += 1;
        this.getOlderRecord();
      }
    }
  },
  methods: {
    // 选择图片
    clickSelectPic() {
      uni.chooseImage({
        count: 9, //选择图片数
        sizaType: ["original", "compressed"],
        sourceType: ["camera", "album"], //从相册还是相机选择
        success: res => {
          console.log(res);
          for (let path in res.tempFilePaths) {
            uni.uploadFile({
              url: this.uploadconfig4.url,
              name: "file",
              filePath: res.tempFilePaths[path],
              header: { Authorization: uni.getStorageSync("token"), platform: 'APP' },
              formData: {},
              success: res => {
                console.log(JSON.parse(res.data));
                try {
                  let data = JSON.parse(res.data);
                  if (data.code !== 0) {
                    return uni.showToast({
                      title: data.message
                    });
                  }
                  this.liuzhuanForm.imgAccessoryBeans.push({
                    url: data.data.url,
                    name: data.data.fileName
                  });
                  console.log(this.liuzhuanForm.imgAccessoryBeans);
                } catch (e) {
                  uni.showToast({
                    title: "上传图片失败" + e.message
                  });
                }
                console.log("success", res);
              },
              fail: res => {
                uni.showToast({
                  title: "上传图片失败" + res
                });
              },
              complete: () => {
                console.log("uploa file complete");
              }
            });
          }
        }
      });
    },
    //点击放大图片
    showBigImg(imgurl, cur) {
      let arr = [];
      imgurl.forEach(item => {
        arr.push(item.url);
      });
      // console.log(imgurl, cur);
      uni.previewImage({
        current: cur,
        loop: true,
        urls: arr
      });
    },
    // 预览上传的文件
    prevFileClick(url, name) {
      prevFile(url, name);
    },
    // 删除附件
    delFile() {
      for (let i = 0; i < this.liuzhuanForm.accessoryBeans.length; i++) {
        this.liuzhuanForm.accessoryBeans.splice(i, 1);
      }
      this.fuckyou();
    },
    // 附件上传恶心的代码块-------------------------------------------------------------
    // 某文件上传结束回调(成功失败都回调)
    onuploadEnd(item) {
      console.log(item);
      // let files = new Map();
      let res = JSON.parse(item.responseText);
      uni.hideLoading();
      if (res.code === 0) {
        console.log(res);
        this.liuzhuanForm.accessoryBeans.push({
          url: res.data.url,
          name: res.data.fileName
        });
        this.suffix = res.data.suffix;
      }
      this.$forceUpdate();
    },
    // 文件选择回调
    onChange(files) {
      uni.showLoading({
        title: "上传中……"
      });
      this.files = files; // 更新选择的文件
      this.$forceUpdate(); // 强制更新视图
    },
    failFile() {
      uni.hideLoading();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci2() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },
    // 强制重置附件按钮,万一出意外点2次按钮至少可以进去
    fuckyou() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },
    // 附件上传恶心的代码块-------------------------------------------------------------
    // 获取最新的通知
    async getNewestRecord() {
      try {
        if (this.applyRecord.length == 0) {
          let res = await getxuanchuanList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            pageSize: 10,
            title: this.keyword
          });
          console.log(res);
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.total = res.total;
          this.applyRecord = [...res.data, ...this.applyRecord];
        } else {
          let res = await getxuanchuanList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            // greaterThan: this.applyRecord[0].id,
            pageSize: 10,
            title: this.keyword
          });
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.applyRecord = [...res.data, ...this.applyRecord];
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取老的数据
    async getOlderRecord() {
      this.moreStatus = "loading";
      try {
        if (this.applyRecord.length == 0) {
          let res = await getxuanchuanList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            title: this.keyword
          });

          this.applyRecord = this.applyRecord.concat(res.data).reverse();
          if (res.data.length < 10) {
            this.moreStatus = "noMore";
          } else {
            this.moreStatus = "more";
          }
        } else {
          let res = await getxuanchuanList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            // lessThan: this.applyRecord[this.applyRecord.length - 1].id,
            pageSize: this.pageSize,
            title: this.keyword
          });

          this.applyRecord = this.applyRecord.concat(res.data).reverse();
          if (res.data.length < 10) {
            this.moreStatus = "noMore";
          } else {
            this.moreStatus = "more";
          }
        }
      } catch (e) {
        uni.showToast({
          title: e.message
        });
      }
    },

    onClickItem(e) {
      console.log(e);
      if (this.currentIndex !== e.currentIndex) {
        this.currentIndex = e.currentIndex;
        // if (this.currentIndex == 1) {
        //   this.getNewestRecord();
        // }
      }
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
      return moment(stamp).format(str);
    },
    async clickApply() {
      if (!this.liuzhuanForm.departmentName)
        return uni.showToast({
          title: "申请部门不能为空",
          icon: "none"
        });
      if (!this.liuzhuanForm.title)
        return uni.showToast({
          title: "请输入主题",
          icon: "none"
        });

      if (this.liuzhuanForm.auditors.length == 0)
        return uni.showToast({
          title: "请选择审核人",
          icon: "none"
        });

      if (this.liuzhuanForm.imgAccessoryBeans.length == 0)
        return uni.showToast({
          title: "请添加图片",
          icon: "none"
        });
      if (this.liuzhuanForm.accessoryBeans.length == 0)
        return uni.showToast({
          title: "请添加附件",
          icon: "none"
        });

      let auditors = [];
      for (let i = 0; i != this.liuzhuanForm.auditors.length; i++) {
        auditors.push({
          ts: "",
          sta: 0,
          msg: "",
          uid: this.liuzhuanForm.auditors[i].uid,
          name: this.liuzhuanForm.auditors[i].name,
          signimg: "",
          stepName:
            this.liuzhuanForm.auditors[i].stepName ||
            this.liuzhuanForm.auditors[i].positionName
        });
      }
      let OldObject = auditors.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: "",
          msg: "",
          sta: 0,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name
        };
        return o;
      }, {});
      const params = {
        departmentId: this.liuzhuanForm.departmentId,
        uid: this.liuzhuanForm.uid,
        title: this.liuzhuanForm.title,
        // departmentName:this.liuzhuanForm.departmentName,
        imgAccessoryBeans: this.liuzhuanForm.imgAccessoryBeans,
        // url: this.liuzhuanForm.pics,
        accessoryBeans: this.liuzhuanForm.accessoryBeans || [],
        approvalProcessDataBeanMap: OldObject
      };
      try {
        await addxuanchuan(params);
          uni.showToast({
            title: "操作成功",
            icon: "success"
          }),

        this.liuzhuanForm = {
          departmentName: "",
          name: "",
          title: "",
          attaches: [],
          auditors: [],
          accessoryBeans: []
        };

        this.currentIndex = 1;
        this.getNewestRecord();
      } catch (err) {
        uni.showToast({
          title: err.message || "error"
        });
      }
    },
    // async revertApply(idx) {
    //   try {
    //     await websock.revertxinjianFawen({
    //       id: this.applyRecord[idx].id
    //     });
    //     this.applyRecord[idx].sta = 4;
    //   } catch (err) {
    //     uni.showToast({
    //       title: err.message || "error"
    //     });
    //   }
    // },
    seeDetail(idx,item) {
      console.log(idx);
      uni.navigateTo({
        url: `/pages/task/xuanchuanbaodaoDetail?content=${JSON.stringify(
          this.applyRecord[idx]
        )}&itemss=${this.currentIndex}&id=${item.id}`
      });
    },
    search() {
      this.applyRecord = [];
      this.getNewestRecord();
    }
  }
};
</script>
  
  <style>
@import "../common/common.css";

/* 封面上传控件 */
::v-deep .file-picker__box {
  position: absolute !important;
  right: 0 !important;
  width: 200rpx !important;
  height: 132rpx !important;
}

::v-deep .file-picker__box-content {
  border: none !important;
}
</style>
  